<template>
  <div class="loan-calculator-tool">
    <div class="tool-header">
      <h1>贷款计算器</h1>
      <p>房贷、车贷等贷款计算工具</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 计算器主体 -->
        <el-col :span="16">
          <div class="calculator-section">
            <!-- 贷款基本信息 -->
            <div class="loan-info">
              <h3>贷款信息</h3>
              <div class="info-inputs">
                <div class="input-group">
                  <label>贷款金额：</label>
                  <el-input-number
                    v-model="loanAmount"
                    :precision="2"
                    :step="1000"
                    :min="0"
                    size="large"
                    placeholder="输入贷款金额"
                    @change="calculateLoan"
                  />
                  <span class="unit">元</span>
                </div>
                <div class="input-group">
                  <label>贷款期限：</label>
                  <el-input-number
                    v-model="loanTerm"
                    :precision="0"
                    :step="1"
                    :min="1"
                    :max="30"
                    size="large"
                    placeholder="输入贷款期限"
                    @change="calculateLoan"
                  />
                  <el-select v-model="termUnit" @change="calculateLoan" size="large">
                    <el-option label="年" value="year" />
                    <el-option label="月" value="month" />
                  </el-select>
                </div>
                <div class="input-group">
                  <label>年利率：</label>
                  <el-input-number
                    v-model="annualRate"
                    :precision="3"
                    :step="0.001"
                    :min="0"
                    :max="1"
                    size="large"
                    placeholder="输入年利率"
                    @change="calculateLoan"
                  />
                  <span class="unit">%</span>
                </div>
                <div class="input-group">
                  <label>还款方式：</label>
                  <el-select v-model="repaymentType" @change="calculateLoan" size="large">
                    <el-option label="等额本息" value="equal_payment" />
                    <el-option label="等额本金" value="equal_principal" />
                  </el-select>
                </div>
              </div>
            </div>
            
            <!-- 计算结果 -->
            <div class="calculation-results" v-if="loanResult">
              <h3>计算结果</h3>
              <div class="result-summary">
                <div class="summary-item">
                  <div class="summary-label">月还款额</div>
                  <div class="summary-value">¥{{ loanResult.monthlyPayment }}</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">总还款额</div>
                  <div class="summary-value">¥{{ loanResult.totalPayment }}</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">总利息</div>
                  <div class="summary-value">¥{{ loanResult.totalInterest }}</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">利息占比</div>
                  <div class="summary-value">{{ loanResult.interestRatio }}%</div>
                </div>
              </div>
              
              <!-- 还款计划表 -->
              <div class="payment-schedule">
                <h4>还款计划表</h4>
                <div class="schedule-table">
                  <div class="table-header">
                    <div class="header-cell">期数</div>
                    <div class="header-cell">月还款额</div>
                    <div class="header-cell">本金</div>
                    <div class="header-cell">利息</div>
                    <div class="header-cell">剩余本金</div>
                  </div>
                  <div 
                    v-for="(payment, index) in loanResult.paymentSchedule.slice(0, 12)" 
                    :key="index"
                    class="table-row"
                  >
                    <div class="cell">第{{ payment.period }}期</div>
                    <div class="cell">¥{{ payment.monthlyPayment }}</div>
                    <div class="cell">¥{{ payment.principal }}</div>
                    <div class="cell">¥{{ payment.interest }}</div>
                    <div class="cell">¥{{ payment.remainingPrincipal }}</div>
                  </div>
                  <div v-if="loanResult.paymentSchedule.length > 12" class="table-note">
                    仅显示前12期，共{{ loanResult.paymentSchedule.length }}期
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 对比分析 -->
            <div class="comparison-analysis" v-if="comparisonResult">
              <h3>还款方式对比</h3>
              <div class="comparison-table">
                <div class="comparison-row">
                  <div class="comparison-label">还款方式</div>
                  <div class="comparison-value">等额本息</div>
                  <div class="comparison-value">等额本金</div>
                </div>
                <div class="comparison-row">
                  <div class="comparison-label">首月还款</div>
                  <div class="comparison-value">¥{{ comparisonResult.equalPayment.firstMonth }}</div>
                  <div class="comparison-value">¥{{ comparisonResult.equalPrincipal.firstMonth }}</div>
                </div>
                <div class="comparison-row">
                  <div class="comparison-label">末月还款</div>
                  <div class="comparison-value">¥{{ comparisonResult.equalPayment.lastMonth }}</div>
                  <div class="comparison-value">¥{{ comparisonResult.equalPrincipal.lastMonth }}</div>
                </div>
                <div class="comparison-row">
                  <div class="comparison-label">总利息</div>
                  <div class="comparison-value">¥{{ comparisonResult.equalPayment.totalInterest }}</div>
                  <div class="comparison-value">¥{{ comparisonResult.equalPrincipal.totalInterest }}</div>
                </div>
                <div class="comparison-row">
                  <div class="comparison-label">利息差额</div>
                  <div class="comparison-value" colspan="2">
                    {{ comparisonResult.interestDifference > 0 ? '等额本息多付' : '等额本金多付' }} 
                    ¥{{ Math.abs(comparisonResult.interestDifference) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 工具和说明 -->
        <el-col :span="8">
          <div class="tools-section">
            <div class="section-header">
              <h3>常用利率</h3>
            </div>
            
            <div class="common-rates">
              <div 
                v-for="rate in commonRates" 
                :key="rate.type"
                class="rate-item"
                @click="setCommonRate(rate.value)"
              >
                <div class="rate-type">{{ rate.type }}</div>
                <div class="rate-value">{{ rate.value }}%</div>
                <div class="rate-desc">{{ rate.description }}</div>
              </div>
            </div>
          </div>
          
          <div class="help-section">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>使用说明</span>
                </div>
              </template>
              
              <div class="help-content">
                <h4>还款方式：</h4>
                <ul>
                  <li><strong>等额本息：</strong> 每月还款金额相同，前期利息多，后期本金多</li>
                  <li><strong>等额本金：</strong> 每月本金相同，利息递减，总利息较少</li>
                </ul>
                
                <h4>计算公式：</h4>
                <ul>
                  <li><strong>等额本息：</strong> 月还款 = 本金 × [月利率×(1+月利率)^期数] / [(1+月利率)^期数-1]</li>
                  <li><strong>等额本金：</strong> 月还款 = 本金/期数 + 剩余本金×月利率</li>
                </ul>
                
                <h4>注意事项：</h4>
                <div class="warning">
                  <p>⚠️ 计算结果仅供参考，实际以银行审批为准</p>
                  <p>⚠️ 利率可能因政策调整而变化</p>
                  <p>⚠️ 提前还款可能产生额外费用</p>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

const loanAmount = ref(1000000)
const loanTerm = ref(30)
const termUnit = ref('year')
const annualRate = ref(0.049)
const repaymentType = ref('equal_payment')

const loanResult = ref(null)
const comparisonResult = ref(null)

const commonRates = [
  { type: '公积金贷款', value: 3.1, description: '5年期以上' },
  { type: '商业贷款', value: 4.9, description: '5年期以上' },
  { type: '车贷', value: 6.0, description: '一般车贷' },
  { type: '消费贷', value: 8.0, description: '个人消费' },
  { type: '经营贷', value: 5.5, description: '企业经营' }
]

const calculateLoan = () => {
  if (!loanAmount.value || !loanTerm.value || !annualRate.value) return
  
  const totalMonths = termUnit.value === 'year' ? loanTerm.value * 12 : loanTerm.value
  const monthlyRate = annualRate.value / 12
  
  if (repaymentType.value === 'equal_payment') {
    calculateEqualPayment(loanAmount.value, totalMonths, monthlyRate)
  } else {
    calculateEqualPrincipal(loanAmount.value, totalMonths, monthlyRate)
  }
  
  // 计算对比分析
  calculateComparison(loanAmount.value, totalMonths, monthlyRate)
}

const calculateEqualPayment = (principal, months, monthlyRate) => {
  const monthlyPayment = principal * (monthlyRate * Math.pow(1 + monthlyRate, months)) / 
                        (Math.pow(1 + monthlyRate, months) - 1)
  
  const totalPayment = monthlyPayment * months
  const totalInterest = totalPayment - principal
  const interestRatio = (totalInterest / totalPayment) * 100
  
  const paymentSchedule = []
  let remainingPrincipal = principal
  
  for (let i = 1; i <= months; i++) {
    const interest = remainingPrincipal * monthlyRate
    const principalPayment = monthlyPayment - interest
    remainingPrincipal -= principalPayment
    
    paymentSchedule.push({
      period: i,
      monthlyPayment: monthlyPayment.toFixed(2),
      principal: principalPayment.toFixed(2),
      interest: interest.toFixed(2),
      remainingPrincipal: Math.max(0, remainingPrincipal).toFixed(2)
    })
  }
  
  loanResult.value = {
    monthlyPayment: monthlyPayment.toFixed(2),
    totalPayment: totalPayment.toFixed(2),
    totalInterest: totalInterest.toFixed(2),
    interestRatio: interestRatio.toFixed(2),
    paymentSchedule: paymentSchedule
  }
}

const calculateEqualPrincipal = (principal, months, monthlyRate) => {
  const monthlyPrincipal = principal / months
  const totalPayment = principal + (principal * monthlyRate * (months + 1) / 2)
  const totalInterest = totalPayment - principal
  const interestRatio = (totalInterest / totalPayment) * 100
  
  const paymentSchedule = []
  let remainingPrincipal = principal
  
  for (let i = 1; i <= months; i++) {
    const interest = remainingPrincipal * monthlyRate
    const monthlyPayment = monthlyPrincipal + interest
    remainingPrincipal -= monthlyPrincipal
    
    paymentSchedule.push({
      period: i,
      monthlyPayment: monthlyPayment.toFixed(2),
      principal: monthlyPrincipal.toFixed(2),
      interest: interest.toFixed(2),
      remainingPrincipal: Math.max(0, remainingPrincipal).toFixed(2)
    })
  }
  
  loanResult.value = {
    monthlyPayment: paymentSchedule[0].monthlyPayment,
    totalPayment: totalPayment.toFixed(2),
    totalInterest: totalInterest.toFixed(2),
    interestRatio: interestRatio.toFixed(2),
    paymentSchedule: paymentSchedule
  }
}

const calculateComparison = (principal, months, monthlyRate) => {
  // 等额本息
  const equalPaymentMonthly = principal * (monthlyRate * Math.pow(1 + monthlyRate, months)) / 
                             (Math.pow(1 + monthlyRate, months) - 1)
  const equalPaymentTotal = equalPaymentMonthly * months
  const equalPaymentInterest = equalPaymentTotal - principal
  
  // 等额本金
  const monthlyPrincipal = principal / months
  const firstMonthPayment = monthlyPrincipal + principal * monthlyRate
  const lastMonthPayment = monthlyPrincipal + monthlyPrincipal * monthlyRate
  const equalPrincipalTotal = principal + (principal * monthlyRate * (months + 1) / 2)
  const equalPrincipalInterest = equalPrincipalTotal - principal
  
  comparisonResult.value = {
    equalPayment: {
      firstMonth: equalPaymentMonthly.toFixed(2),
      lastMonth: equalPaymentMonthly.toFixed(2),
      totalInterest: equalPaymentInterest.toFixed(2)
    },
    equalPrincipal: {
      firstMonth: firstMonthPayment.toFixed(2),
      lastMonth: lastMonthPayment.toFixed(2),
      totalInterest: equalPrincipalInterest.toFixed(2)
    },
    interestDifference: equalPaymentInterest - equalPrincipalInterest
  }
}

const setCommonRate = (rate) => {
  annualRate.value = rate / 100
  calculateLoan()
  ElMessage.success(`已设置利率为${rate}%`)
}

// 初始化计算
calculateLoan()
</script>

<style scoped>
.loan-calculator-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.calculator-section,
.tools-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.loan-info,
.calculation-results,
.comparison-analysis {
  margin-bottom: 30px;
}

.loan-info h3,
.calculation-results h3,
.comparison-analysis h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.3rem;
}

.info-inputs {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.input-group label {
  min-width: 80px;
  font-weight: 500;
  color: #666;
}

.input-group .el-input-number,
.input-group .el-select {
  flex: 1;
}

.unit {
  color: #666;
  font-weight: 500;
}

.result-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.summary-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  border: 1px solid #e9ecef;
}

.summary-label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 1.5rem;
  font-weight: bold;
  color: #667eea;
}

.payment-schedule {
  margin-top: 30px;
}

.payment-schedule h4 {
  color: #333;
  margin-bottom: 15px;
  font-size: 1.1rem;
}

.schedule-table {
  background: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e9ecef;
}

.table-header {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
  background: #667eea;
  color: white;
  font-weight: bold;
}

.header-cell {
  padding: 12px;
  text-align: center;
  border-right: 1px solid rgba(255, 255, 255, 0.2);
}

.header-cell:last-child {
  border-right: none;
}

.table-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
  border-bottom: 1px solid #e9ecef;
}

.table-row:last-child {
  border-bottom: none;
}

.cell {
  padding: 12px;
  text-align: center;
  border-right: 1px solid #e9ecef;
  background: white;
}

.cell:last-child {
  border-right: none;
}

.table-note {
  padding: 10px;
  text-align: center;
  color: #666;
  font-size: 0.9rem;
  background: #f8f9fa;
}

.comparison-table {
  background: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e9ecef;
}

.comparison-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  border-bottom: 1px solid #e9ecef;
}

.comparison-row:last-child {
  border-bottom: none;
}

.comparison-label {
  padding: 15px;
  background: #667eea;
  color: white;
  font-weight: bold;
  text-align: center;
}

.comparison-value {
  padding: 15px;
  text-align: center;
  background: white;
  border-right: 1px solid #e9ecef;
}

.comparison-value:last-child {
  border-right: none;
}

.comparison-row:last-child .comparison-value {
  grid-column: span 2;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.common-rates {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.rate-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.rate-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.rate-type {
  font-size: 1rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.rate-value {
  font-size: 1.2rem;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 5px;
}

.rate-desc {
  font-size: 0.9rem;
  color: #666;
}

.help-section {
  margin-top: 20px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.help-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.help-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.help-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .info-inputs {
    grid-template-columns: 1fr;
  }
  
  .input-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .input-group label {
    min-width: auto;
  }
  
  .result-summary {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .table-header,
  .table-row {
    grid-template-columns: 1fr;
  }
  
  .header-cell,
  .cell {
    border-right: none;
    border-bottom: 1px solid #e9ecef;
  }
  
  .comparison-row {
    grid-template-columns: 1fr;
  }
  
  .comparison-value {
    border-right: none;
    border-bottom: 1px solid #e9ecef;
  }
}
</style>
